<?php

namespace app\api\Service;

use app\api\controller\Order;
use think\Db;
use think\cache\driver\Redis;
use app\common\library\Auth;
use function Symfony\Component\Translation\t;

class MatchingOrderService
{
    // 更新坐标
    public static function updateCoordinates($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $lng = $data['lng'];
        $lat = $data['lat'];
        if( !$lng || !$lat ) return ['code'=>0,'msg'=>'坐标无效','data'=>''];
        $result = \app\admin\model\Steward::where('id',$steward_id)->update(['lng'=>$lng,'lat'=>$lat, 'updatetime'=>time()]);
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 获取服务时间
    public static function getServiceTime($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $service = \app\admin\model\Steward::where('id',$steward_id)->field('service_switch,start,over')->find();

        return ['code'=>1,'msg'=>'查询成功','data'=>$service];

    }

    // 设置服务时间
    public static function setServiceTime($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $service_switch = $data['service_switch'];
        if( !$service_switch ) return ['code'=>0,'msg'=>'无效参数','data'=>''];

        if( $service_switch == 3 ){
            $start = isset($data['start']) ? $data['start'] : '';
            $over = isset($data['over']) ? $data['over'] : '';
            if( !$start ) return ['code'=>0,'msg'=>'请设置开始时间','data'=>''];
            if( !$over  ) return ['code'=>0,'msg'=>'请设置结束时间','data'=>''];
            $start_time = strtotime(date('Y-m-d ').$start);
            $over_time = strtotime(date('Y-m-d ').$over);
            if( $start_time >= $over_time ) return ['code'=>0,'msg'=>'结束时间必须大于开始时间','data'=>''];
            $result = \app\admin\model\Steward::where('id',$steward_id)->update(['service_switch'=>$service_switch,'start'=>$start,'over'=>$over,'updatetime'=>time()]);
        }else{
            $result = \app\admin\model\Steward::where('id',$steward_id)->update(['service_switch'=>$service_switch,'updatetime'=>time()]);
        }

        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        } else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }


    // 匹配订单列表（没有加倒计时时间戳，没有检测是否在服务中，没有去掉被人接走的单子）
    public static function matchingOrderList($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $steward = \app\admin\model\Steward::where('id',$steward_id)->field('type,lng,lat')->find();
        $type = $steward['type'];
        $lng = $steward['lng'];
        $lat = $steward['lat'];
        if(!$type) return ['code'=>0,'msg'=>'数据异常','data'=>''];
        if(!$lng) return ['code'=>0,'msg'=>'定位数据异常.','data'=>''];
        if(!$lat) return ['code'=>0,'msg'=>'定位数据异常。','data'=>''];

        // 检测管家是否在服务状态
        $result = self::checkServiceStatus($steward_id);
        if ( !$result ) return ['code'=>1,'msg'=>'管家已休息','data'=>[]];// 为了前端不弹窗code改为1,data返回空数组

        // 根据经纬度获取管家周边5km内且预约时间2小时内的订单
        $order = self::getRecentlyOrder($type,$lng,$lat,5);

        return ['code'=>1,'msg'=>'查询成功','data'=>$order];
    }

    // 管家抢单
    public static function orderGrabbing($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $order_id = $data['order_id'];

        // 检测管家是否在服务状态
        $result = self::checkServiceStatus($steward_id);
        if ( !$result ) return ['code'=>0,'msg'=>'管家已休息','data'=>''];

        if (!$order_id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }

        try{

            //判断订单是否存在
            $order = \app\admin\model\Order::where(['id'=>$order_id,'paid'=>1,'status'=>0])->lock(true)->find();
            if (!$order) {
                return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
            }
            if(time() > $order['reservedtime']){
                return ['code' => 0, 'msg' => '已超过预约时间', 'data' => ''];
            }
            // 修改订单信息
            $overtime = time() + $order->service_duration * 3600;
            $result = \app\admin\model\Order::where('id', $order_id)->update(['steward_id'=>$steward_id,'status'=>1,'receivetime'=>time(),'overtime'=>$overtime,'updatetime'=>time()]);
            // 修改自身状态
            \app\admin\model\Steward::where(['id'=>$steward_id])->update(['service_status'=>2,'updatetime'=>time()]);
            // 用户发送通知
            $mobile = \app\admin\model\User::where(['id'=>$order->user_id])->value('mobile');
            sendSmsNotice($mobile,1);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 管家出发
    public static function orderDeparture($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $order_id = $data['order_id'];

        if (!$order_id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }

        try{

            //判断订单是否存在
            $order = \app\admin\model\Order::where(['id'=>$order_id,'steward_id'=>$steward_id,'paid'=>1,'status'=>1])->lock(true)->find();
            if (!$order) {
                return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
            }
            // 修改订单状态
            $result = \app\admin\model\Order::where('id', $order_id)->update(['status'=>2,'updatetime'=>time()]);
            // 用户发送通知
            $mobile = \app\admin\model\User::where(['id'=>$order->user_id])->value('mobile');
            sendSmsNotice($mobile,2);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 管家到达
    public static function orderArrive($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $order_id = $data['order_id'];

        if (!$order_id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }

        try{

            //判断订单是否存在
            $order = \app\admin\model\Order::where(['id'=>$order_id,'steward_id'=>$steward_id,'paid'=>1,'status'=>2])
                ->lock(true)->find();
            if (!$order) {
                return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
            }
            // 修改订单状态
            $result = \app\admin\model\Order::where('id', $order_id)->update(['status'=>3,'reachtime'=>time(),'updatetime'=>time()]);
            // 用户发送通知
            $mobile = \app\admin\model\User::where(['id'=>$order->user_id])->value('mobile');
            sendSmsNotice($mobile,3);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 学生拍照
    public static function studentPhoto($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $order_id = $data['order_id'];
        $photo = $data['photo'];

        if (!$order_id) {
            return ['code' => 0, 'msg' => '请选择要操作的订单', 'data' => ''];
        }

        try{

            //判断订单是否存在
            $order = \app\admin\model\Order::where(['id'=>$order_id,'steward_id'=>$steward_id,'paid'=>1,'status'=>3])
                ->lock(true)->find();
            if (!$order) {
                return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
            }

            $result = \app\admin\model\Order::where('id', $order_id)->update(['student_photo'=>$photo, 'updatetime'=>time()]);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 管家订单列表 state "-1":__('待付款'),"0":__('待接单'),"1":__('服务中'),"2":__('已完成'),"7":__('已取消')
    public static function stewardOrderList($data)
    {
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $where['steward_id'] = $steward_id;
//        $where['deletetime'] = null;

        if( strlen($data['state']) && $data['state'] == 0){
            $where['paid'] = 1;$where['status'] = 0;
        }
        if(isset($data['state']) && $data['state'] == 1){
            $where['paid'] = 1;$where['status'] = ['IN', '1,2,3,4'];
        }
        if(isset($data['state']) && $data['state'] == 2){
            $where['paid'] = 1;$where['status'] = 5;
        }
        if(isset($data['state']) && $data['state'] == 7){
            $where['status'] = ['IN', '100,101,102,103'];
        }
        if(isset($data['state']) && $data['state'] == -1){
            $where['paid'] = 0;$where['status'] = 0;
        }

        $list = \app\admin\model\Order::where($where)->order('reservedtime desc')->field('id,student_name,school_addr,home_addr,service_id,coupon_price,total_price,pay_price,paid,status,reservedtime')
            ->paginate($limit)->each(
                function($item){
                    $item['service_name'] = \app\admin\model\ServicePackage::where(['id'=>$item['service_id']])->value('title');

                    if($item['pay_price'] == 0) {
                        $item['pay_price'] = round(bcsub($item['total_price'], $item['coupon_price'], 3),2);
                    }

                    $item['reservedtime_text'] = date('Y-m-d H:i', $item['reservedtime']);

                    return $item;
                }
            );

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 管家订单详情 state "-1":__('待付款'),"0":__('待接单'),"1":__('服务中'),"2":__('已完成'),"7":__('已取消')
    public static function stewardOrderDetail($data)
    {
        $auth = Auth::instance();
        $steward_id = $auth->getStewardId();
        $order_id = $data['order_id'];

        $detail = \app\admin\model\Order::where(['id'=>$order_id])->field('id,steward_id,student_name,student_photo,school_addr,home_addr,service_id,mark,reservedtime,reservedforte,service_fee,travel_expenses,coupon_id,coupon_price,total_price,pay_price,order_no,createtime,paidtime,receivetime,reachtime,dealtime,paid,status,contract')
            ->find();

        if($detail){
            $stewardInfo = \app\admin\model\Steward::where(['id'=>$detail['steward_id']])->field('lng,lat,realname,avatar,age,forte,gender')->find();
            if($stewardInfo){
                $detail['steward_lng'] = $stewardInfo['lng'];
                $detail['steward_lat'] = $stewardInfo['lat'];
                $detail['steward_name'] = $stewardInfo['realname'];
                $detail['steward_avatar'] = $stewardInfo['avatar'];
                $detail['steward_age'] = $stewardInfo['age'];
                $detail['steward_gender'] = $stewardInfo['gender'];
                $detail['steward_forte'] = explode(',',$stewardInfo['forte']);
            }else{
                $detail['steward_lng'] = '';
                $detail['steward_lat'] = '';
                $detail['steward_name'] = '';
                $detail['steward_avatar'] = '';
                $detail['steward_age'] = '';
                $detail['steward_gender'] = '';
                $detail['steward_forte'] = '';
            }
            $service = \app\admin\model\ServicePackage::where(['id'=>$detail['service_id']])->field('title,image')
                ->find();
            if($service){
                $detail['service_title'] = $service['title'];
                $detail['service_image'] = $service['image'];
            }else{
                $detail['service_title'] = '服务';
            }
            if($detail['pay_price'] == 0){
                $detail['pay_price'] = round(bcsub($detail['total_price'], $detail['coupon_price'], 3),2);
            }
            if($detail['status'] == 5){
                $detail['contract'] = '';
            }

            $detail['reservedtime_text'] = date('Y-m-d H:i', $detail['reservedtime']);
            $coupon_name = \app\admin\model\Coupon::where(['id'=>$detail['coupon_id']])->value('name');
            if($coupon_name){
                $detail['coupon_name'] = $coupon_name;
            }else{
                $detail['coupon_name'] = '优惠劵';
            }
            $detail['createtime_text'] = date('Y-m-d H:i', $detail['createtime']);
            if($detail['paidtime']){
                $detail['paidtime_text'] = date('Y-m-d H:i', $detail['paidtime']);
            }else{
                $detail['paidtime_text'] = '';
            }
            if($detail['receivetime']){
                $detail['receivetime_text'] = date('Y-m-d H:i', $detail['receivetime']);
            }else{
                $detail['receivetime_text'] = '';
            }
            if($detail['reachtime']){
                $detail['reachtime_text'] = date('Y-m-d H:i', $detail['reachtime']);
            }else{
                $detail['reachtime_text'] = '';
            }
            if($detail['dealtime']){
                $detail['dealtime_text'] = date('Y-m-d H:i', $detail['dealtime']);
            }else{
                $detail['dealtime_text'] = '';
            }

            // 有没有加钟
            $extra = \app\admin\model\OrderExtra::where(['order_id'=>$order_id,'paid'=>1])->field('id,title,duration,price')
                ->select();
            if($extra){
                $detail['extra'] = $extra;
            }else{
                $detail['extra'] = [];
            }

            unset($detail['service_id']);
            unset($detail['coupon_id']);
            unset($detail['createtime']);
            unset($detail['paidtime']);
            unset($detail['receivetime']);
            unset($detail['reachtime']);
            unset($detail['dealtime']);
        }
        return ['code'=>1,'msg'=>'查询成功','data'=>$detail];
    }














    // 检测管家是否在服务状态
    public static function checkServiceStatus($steward_id){
        $steward = \app\admin\model\Steward::where('id',$steward_id)->field('service_switch,start,over')->find();
        $service_switch = $steward['service_switch'];
        $start = $steward['start'];
        $over = $steward['over'];
        if($service_switch == 1){
            return false;
        }
        if($service_switch == 2){
            return true;
        }
        if($service_switch == 3){
            $start_time = strtotime(date('Y-m-d ').$start);
            $over_time = strtotime(date('Y-m-d ').$over);
            if(time() >= $start_time && time() <= $over_time){
                return true;
            } else {
                return false;
            }
        }
    }

    // 获取距离最近的单子
    public static function getRecentlyOrder($type,$longitude,$latitude,$distance){
         $start = strtotime(date('Y-m-d H').':00');
         $over = $start + 3600 * 2;

        //计算最大最小经纬度范围
        $range  = 180 / pi() * $distance / 6378.138; //搜索 N km 之内
        $lngR   = $range / cos($latitude * pi() / 180);
        $maxLat = $latitude + $range; //最大纬度
        $minLat = $latitude - $range; //最小纬度
        $maxLng = $longitude + $lngR; //最大经度
        $minLng = $longitude - $lngR; //最小经度
//        return ['maxLat' => $maxLat,'minLat' => $minLat,'maxLng' => $maxLng,'minLng' => $minLng];
        //查找经纬度符合条件的数据
        $list = \app\admin\model\Order::alias('o')->join('__STUDENT__ s ','o.student_id= s.id')
            ->where(['s.school_lng'=>['between',[$minLng,$maxLng]]])
            ->where(['s.school_lat'=>['between',[$minLat,$maxLat]]])
            ->where(['o.paid'=>1,'o.status'=>0])
            ->where(['o.service_type'=>['<=',$type]])
            ->where('o.deletetime',null)
            ->whereTime('o.reservedtime', 'between', [$start, $over])
            ->field('o.id,o.reservedtime,o.school_addr,o.home_addr,o.pay_price,o.paid,o.status')
            ->orderRaw('rand()')->limit(10)
            ->select();

        // 按预约时间排序
        $list = self::arraySort($list,'reservedtime');

        foreach($list as &$item){
            $item['reservedtime_text'] = date('Y-m-d H:i:s', $item['reservedtime']);
        }
        return $list;
    }

    // 二维数组排序方法
    public static function arraySort($arr, $field, $sort = SORT_ASC){
        $key = array_column($arr, $field);
        array_multisort($key, $sort, $arr);
        return $arr;
    }

}